package dbx;

import stdx.Utils;
import stdx.ResPool;
import java.io.Closeable;
import java.util.HashMap;
import redis.clients.jedis.Jedis;

public class RedisConnect extends Jedis implements ResPool.Resource{
	public static class Pool extends ResPool{
		protected int port;
		protected String host;
		protected boolean ssl;
		protected String passwd;

		public Resource create() throws Exception{
			String msg = null;
			RedisConnect conn = new RedisConnect(host, port, ssl);

			try{
				if (passwd == null || passwd.isEmpty()){
					msg = conn.ping();
				}
				else{
					msg = conn.auth(passwd);
				}

				return conn;
			}
			catch (Exception e){
				e.printStackTrace();
				conn.close();
				throw e;
			}
		}
		public RedisConnect get() throws Exception{
			return (RedisConnect)super.get();
		}
		public boolean checkSuccess(Closeable conn){
			if (conn == null) return false;
			RedisConnect tmp = (RedisConnect)(conn);
			return tmp.client.isBroken() ? false : true;
		}
		public Pool init(String host, int port, String passwd, boolean ssl){
			this.destroy();
			this.ssl = ssl;
			this.host = host;
			this.port = port;
			this.passwd = passwd;
			return this;
		}
	}

	protected ResPool pool;
	protected static Pool defaultpool = new Pool();
	protected static HashMap<String, Pool> poolmap = new HashMap<String, Pool>();

	public void close(){
		if (pool == null){
			super.close();
		}
		else{
			pool.release(this);
		}
	}
	public void setPool(ResPool pool){
		this.pool = pool;
	}
	public RedisConnect(String host, int port){
		super(host, port);
	}
	public RedisConnect(String host, int port, boolean ssl){
		super(host, port, ssl);
	}

	public static Pool GetPool(){
		return defaultpool;
	}
	public static Pool GetPool(String name){
		synchronized(poolmap){
			Pool pool = poolmap.get(name);

			if (pool == null){
				pool = new Pool();
				poolmap.put(name, pool);
			}

			return pool;
		}
	}
	public static RedisConnect Connect() throws Exception{
		return defaultpool.get();
	}
	public static RedisConnect Connect(String name) throws Exception{
		return GetPool(name).get();
	}
}
